package com.javaweb.dao.impl;

import com.javaweb.dao.TagDao;
import com.javaweb.model.Tag;
import com.javaweb.service.dto.TagDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * @author Wanghai
 * @date 2024/10/13
 */

@Repository
public class TagDaoImpl implements TagDao {
    @Autowired
    JdbcTemplate jdbcTemplate ;

    @Override
    public int insert(Tag tag) {
        String sql="insert into tb_tag(name,create_time,update_time)" +
                "values (?,?,?)";
        Object [] args = new Object[]{
                tag.getName(),
                new java.sql.Date(tag.getCreateTime().getTime()),
                new java.sql.Date(tag.getUpdateTime().getTime())}
                ;
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int insertArticleTag(Integer articleId, Integer tagid) {
        String sql="insert into tb_article_tag(article_id,tag_id)" +
                "values (?,?)";
        Object [] args = new Object[]{articleId,tagid};
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public List<Tag> findAllTags() {
        String sql = "SELECT * FROM tb_tag"; // 假设表名为 tag
        return jdbcTemplate.query(sql, new TagRowMapper());
    }

    // 自定义 RowMapper 实现
    private static class TagRowMapper implements RowMapper<Tag> {
        @Override
        public Tag mapRow(ResultSet rs, int rowNum) throws SQLException {
            Tag tag = new Tag();
            tag.setId(rs.getInt("id"));
            tag.setName(rs.getString("name"));
            tag.setCreateTime(rs.getTimestamp("create_time"));
            tag.setUpdateTime(rs.getTimestamp("update_time"));
            return tag;
        }
    }

    @Override
    public boolean deleteTagById(String tagId) {
        String sql = "DELETE FROM tb_tag WHERE id = ?";
        int rowsAffected = jdbcTemplate.update(sql, tagId);
        return rowsAffected > 0; // 如果删除成功，返回 true
    }

    @Override
    public int addTag(TagDto tagDto) {
        String sql = "INSERT INTO tb_tag (name ) VALUES ( ?)";
        return jdbcTemplate.update(sql, tagDto.getName());
    }

    @Override
    public void deleteTag(String tagId) {

    }
}
